//
//  FSPrivacyAlertViewController.m
//  FSiOSClient
//
//  Created by purlible on 2024/8/27.
//

#import "FSPrivacyAlertViewController.h"
#import <YYText/YYText.h>
#import "FSWebViewController.h"
#import "AppDelegate.h"

@interface FSPrivacyAlertViewController ()

@property (nonatomic, weak) id<FSPrivacyAlertViewDelegate> delegate;

@property (nonatomic, weak) UIView *bgView;
@property (nonatomic, weak) UIView *alertView;

@property (nonatomic, weak) UILabel *titleLabel;
@property (nonatomic, weak) YYLabel *yyLabel;
@property (nonatomic, weak) UIButton *disBtn;

@end

@implementation FSPrivacyAlertViewController


+ (BOOL) isAgreed
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *agreed = [userDefault objectForKey:kHCBootPrivacyAgreed];
    if (!isNull(agreed) && !!agreed.length)
    {
        NSString *currentVersion =  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

        if ([agreed isEqualToString:currentVersion])
        {
            return YES;
        }
    }
    return NO;
}

+ (BOOL) tryShowPrivacyAlertWithController:(UIViewController *)conterller delegate:(id<FSPrivacyAlertViewDelegate>)delegate
{
    FSPrivacyAlertViewController *alert = [FSPrivacyAlertViewController create];
    alert.targetVC = conterller;
    alert.delegate = delegate;
    [alert show];

    return YES;
}

+(instancetype) create
{
    FSPrivacyAlertViewController* vc =  [[FSPrivacyAlertViewController alloc] init];
    return vc;
}

-(instancetype) init
{
    self = [super init];
    if(self)
    {
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    [self initViews];
    
    self.alertView.transform = CGAffineTransformMakeScale(0, 0);
    self.bgView.alpha = 0;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)initViews {
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = RGBA(0, 0, 0, 0.6);
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    self.bgView = bgView;
    
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 7;
    view.clipsToBounds = YES;
    [bgView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.scale_offset(42);
        make.right.scale_offset(-42);
    }];
    self.alertView = view;
    
    UILabel *title = ({
        UILabel *v = [UILabel new];
        v.font = FONT_SIZE_16;
        v.textColor = UIColorHex(#161413);
        v.text = NSLocalizedString(@"privacy_title", nil) ;
        v;
    });
    [view addSubview:title];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.scale_offset(28);
        make.centerX.offset(0);
    }];
    self.titleLabel = title;
    
    NSString *contentStr = NSLocalizedString(@"privacy_agreement_info", nil);
    
    NSMutableAttributedString *text  = [[NSMutableAttributedString alloc] initWithString:contentStr];
    text.yy_font = FONT_SIZE_13;
    text.yy_color = UIColorHex(#666666);
    text.yy_lineSpacing = 5.f;
    text.yy_firstLineHeadIndent = 32;
    
    NSRange range = [contentStr rangeOfString:@"《隐私政策》"];
    if (![FSTools isCurrentLanguageSimplifiedChinese])
    {
        range = [contentStr rangeOfString:@"'Privacy Policy'"];
    }
    [text yy_setTextHighlightRange:range
                             color:UIColorHex(#4496f3)
                   backgroundColor:[UIColor clearColor]
                         tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect)
     {
        
        FSWebModel *webModel = [FSWebModel new];
        webModel.autoTitle = @"隐私政策";
        webModel.localUrlName = @"privacy_agreement_zh";
        if (![FSTools isCurrentLanguageSimplifiedChinese])
        {
            webModel.autoTitle = @"Privacy Policy";
            webModel.localUrlName = @"privacy_agreement_en";
        }
        
        FSWebViewController *webVc = [[FSWebViewController alloc] initWithModel:webModel];
        [self.navigationController pushViewController:webVc animated:YES];
    }];
    
    range = [contentStr rangeOfString:@"《用户协议》"];
    if (![FSTools isCurrentLanguageSimplifiedChinese])
    {
        range = [contentStr rangeOfString:@"'User Agreement'"];
    }
    [text yy_setTextHighlightRange:range
                             color:UIColorHex(#4496f3)
                   backgroundColor:[UIColor clearColor]
                         tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect)
     {
        
        FSWebModel *webModel = [FSWebModel new];
        webModel.autoTitle = @"用户协议";
        webModel.localUrlName = @"user_agreement_zh";
        if (![FSTools isCurrentLanguageSimplifiedChinese])
        {
            webModel.autoTitle = @"User Agreement";
            webModel.localUrlName = @"user_agreement_en";
        }
        
        FSWebViewController *webVc = [[FSWebViewController alloc] initWithModel:webModel];
        [self.navigationController pushViewController:webVc animated:YES];
    }];
    
    
    YYLabel *yyLabel = ({
        YYLabel *v = [YYLabel new];
        v.userInteractionEnabled = YES;
        v.preferredMaxLayoutWidth = SCREEN_WIDTH - scale_by_screen_width(118.f);
        v.numberOfLines = 0;
        v.attributedText = text;
        v;
    });
    [view addSubview:yyLabel];
    [yyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(title.mas_bottom).scale_offset(10);
        make.left.scale_offset(17);
        make.right.scale_offset(-17);
    }];
    self.yyLabel = yyLabel;
    
    UIButton *btn = [UIButton new];
    btn.titleLabel.font = FONT_SIZE_16;
    btn.titleLabel.adjustsFontSizeToFitWidth = YES;
    btn.layer.cornerRadius = 18;
    btn.backgroundColor = UIColorHex(#4496f3);
    [btn setTitle:NSLocalizedString(@"privacy_btn_agree", nil) forState:UIControlStateNormal];
    [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(agreen) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.yyLabel.mas_bottom).scale_offset(25);
        make.centerX.offset(0);
        make.width.scale_offset(230);
        make.height.scale_offset(36);
    }];
    
    UIButton *disagreenBtn = [UIButton new];
    disagreenBtn.titleLabel.font = FONT_SIZE_16;
    disagreenBtn.layer.cornerRadius = 18;
    disagreenBtn.layer.borderColor = UIColorHex(#4496f3).CGColor;
    disagreenBtn.layer.borderWidth = 0.5;
    [disagreenBtn setTitle:NSLocalizedString(@"privacy_btn_disagree", nil) forState:UIControlStateNormal];
    [disagreenBtn setTitleColor:UIColorHex(#4496f3) forState:UIControlStateNormal];
    [disagreenBtn addTarget:self action:@selector(disagreen) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:disagreenBtn];
    [disagreenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btn.mas_bottom).scale_offset(15);
        make.centerX.offset(0);
        make.width.scale_offset(230);
        make.height.scale_offset(36);
        make.bottom.scale_offset(-23);
    }];
    self.disBtn = disagreenBtn;
}


#pragma mark -

- (void)agreen
{
    [self hideAnimation:YES];
}

- (void)disagreen
{
    [self hideAnimation:NO];
}

#pragma mark - show & hide

- (void)show
{
    FSWeakSelf
    UIViewController *topVC = [self topViewController];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:weakSelf];
    nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [topVC presentViewController:nav animated:NO completion:^{
        [weakSelf showAnimation];
    }];
}

- (UIViewController *)topViewController {
    UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

- (void)hide:(BOOL)agreen
{
    [self dismissViewControllerAnimated:NO completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(self.delegate)
            {
                [self.delegate privacyAlertViewDidAgreed:agreen];
            }
        });
    }];
}

- (void)showAnimation {
    FSWeakSelf
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.alertView.transform = CGAffineTransformMakeScale(1.1, 1.1);
        weakSelf.bgView.alpha = 1;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1f animations:^{
            weakSelf.alertView.transform = CGAffineTransformIdentity;
        }];
    }];
}

- (void)hideAnimation:(BOOL)agreen {
    FSWeakSelf
    [UIView animateWithDuration:0.15 animations:^{
        weakSelf.alertView.transform = CGAffineTransformMakeScale(0.05, 0.05);
        weakSelf.bgView.alpha = 0;
    } completion:^(BOOL finished) {
        [weakSelf hide:agreen];
    }];
}


@end
